using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

/// <summary>
///     略知CSharp http://blog.csdn.net/subsystemp
/// </summary>
public class ScrollRectHelper : MonoBehaviour, IBeginDragHandler, IEndDragHandler
{
    public float smooting = 5;

    //滑动速度
    public float itemCount;

    //scrollview item
    public int pageCount = 1;

    //总页数
    private bool isDrag;

    //是否拖拽结束
    private readonly List<float> listPageValue = new() { 0 };

    //滑动的目标位置
    private float nowindex;

    private float pageIndex;
    //每页显示的项目

    private ScrollRect srect;

    //总页数索引比列 0-1
    private float targetPos;
    //当前位置索引

    private void Awake()
    {
        srect = GetComponent<ScrollRect>();
        ListPageValueInit();
    }

    private void Update()
    {
        if (!isDrag)
            srect.horizontalNormalizedPosition =
                Mathf.Lerp(srect.horizontalNormalizedPosition, targetPos, Time.deltaTime * smooting);
    }

    /// <summary>
    ///     拖动开始
    /// </summary>
    /// <param name="eventData"></param>
    public void OnBeginDrag(PointerEventData eventData)
    {
        isDrag = true;
    }

    /// <summary>
    ///     拖拽结束
    /// </summary>
    /// <param name="eventData"></param>
    public void OnEndDrag(PointerEventData eventData)
    {
        isDrag = false;
        var tempPos = srect.horizontalNormalizedPosition; //获取拖动的值
        var index = 0;
        var offset = Mathf.Abs(listPageValue[index] - tempPos); //拖动的绝对值
        for (var i = 1; i < listPageValue.Count; i++)
        {
            var temp = Mathf.Abs(tempPos - listPageValue[i]);
            if (temp < offset)
            {
                index = i;
                offset = temp;
            }
        }

        targetPos = listPageValue[index];
        nowindex = index;
    }

    //每页比例
    private void ListPageValueInit()
    {
        pageIndex = itemCount / pageCount - 1;
        for (float i = 1; i <= pageIndex; i++) listPageValue.Add(i / pageIndex);
    }

    public void BtnLeftGo()
    {
        nowindex = Mathf.Clamp(nowindex - 1, 0, pageIndex);
        targetPos = listPageValue[Convert.ToInt32(nowindex)];
    }

    public void BtnRightGo()
    {
        nowindex = Mathf.Clamp(nowindex + 1, 0, pageIndex);
        targetPos = listPageValue[Convert.ToInt32(nowindex)];
    }
}